import React,{useState,useEffect} from 'react';
import logoimg from '../assets/img/logo.jpg';

import { Menu, Dropdown,message} from 'antd';
import { CaretDownOutlined } from '@ant-design/icons';
import defaultAvatar from '../assets/img/login.jpg'
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';

const Header = (props) => {
const navigate = useNavigate()
const [avatar,setavatar] = useState(defaultAvatar)
const [username,setusername] = useState('游客')

// 模拟componentDidMounted
useEffect(()=>{
  let username1 =  localStorage.getItem('username')
  let avatar1 =  localStorage.getItem('avatar')
  if(username1){
    setusername(username1)
  }
  if(avatar1){
    setavatar('http://47.93.114.103:6688/'+avatar1)
  }
},[props.mykey])

// 退出登录
const logout=()=>{
  localStorage.clear()  //清除本地存储中的数据
  message.success('退出成功，正在返回登录页')
  setTimeout(()=>navigate('/login'),1500)
}
  const menu = (
    <Menu>
      <Menu.Item key={1}>修改资料</Menu.Item>
      <Menu.Divider />
      <Menu.Item key={2} onClick={logout}>退出登录</Menu.Item>
    </Menu>
  );

  return (
    <header>
        <img src={logoimg} alt="" />
        <span>后台文章管理系统</span>
       <div className='right'>
       <Dropdown overlay={menu}>
       <a className="ant-dropdown-link" 
       onClick={e => e.preventDefault()}>
         <img src={avatar} alt=""/>
         <span>{username}</span> 
         <CaretDownOutlined />
         </a>
  </Dropdown>,

       </div>
      </header>
  );
}
const mapStateToProps = (state)=>{
  return {
    mykey:state.mykey
  }
}

export default connect(mapStateToProps)( Header);
